package sk.naive.talker.server;

import sk.naive.talker.*;
import sk.naive.talker.TimerTask;

import java.util.*;

/**
 * Timer.
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.2 $ $Date: 2005/01/12 20:14:53 $
 */
public class Timer implements TimerService {
	private java.util.Timer timer;

	private List<TimerTask> tasks;

	public Timer(String name) {
		tasks = new LinkedList<TimerTask>();
		timer = new java.util.Timer(name, true);
	}

	public void schedule(TimerTask task, long delay) {
		timer.schedule(task, delay);
		addTask(task);
	}

	public void schedule(TimerTask task, Date time) {
		timer.schedule(task, time);
		addTask(task);
	}

	public void schedule(TimerTask task, long delay, long period) {
		timer.scheduleAtFixedRate(task, delay, period);
		addTask(task);
	}

	public void schedule(TimerTask task, Date time, long period) {
		timer.scheduleAtFixedRate(task, time, period);
		addTask(task);
	}

	private void addTask(TimerTask task) {
		task.setTimerService(this);
		tasks.add(task);
	}

	public void remove(TimerTask task) {
		if (tasks != null && tasks.contains(task)) {
			tasks.remove(task);
			task.cancel();
		}
	}

	public void cancel() {
		timer.cancel();
		tasks = null;
	}

	public List<TimerTask> tasks() {
		return Collections.unmodifiableList(tasks);
	}
}
